from datetime import timedelta

from sqlalchemy.orm import Session

from controller.PublicAdminController import PublicAdminController
from crud import UserAdminCrud
from model.EnumDefine import UserStatus
from schema.ParamSchema import UserInfo, UserModPwdInfo, PortMenusInfo
from util.Auth import get_password_hash, authenticate_user, create_access_token, ACCESS_TOKEN_EXPIRE_MINUTES
from util.ErrorCode import ErrorCode


class UserAdminController:

    @staticmethod
    def add_user(userInfo: UserInfo, db: Session):
        if PublicAdminController.check_phone_num(userInfo.user_id):
            if len(userInfo.user_id) == 0 or len(userInfo.password) == 0:
                return {"code": ErrorCode.USERID_OR_PASSWORD_ERROR.value, "message": "用户名或密码不能为空"}
            else:
                response = UserAdminCrud.query_user_by_userid(userInfo.user_id, db)
                if response.get('code') == 0:
                    data = response.get('data')
                    if data is not None:
                        return {"code": ErrorCode.USERID_ALREADY_EXISTS.value, "message": "用户名已存在"}
                    else:
                        userInfo.password = get_password_hash(userInfo.password)
                        return UserAdminCrud.add_user(userInfo, db)
                else:
                    return response
        else:
            return {"code": ErrorCode.USERID_NOT_INVALID.value, "message": "用户名不合法，格式为手机号"}

    @staticmethod
    def mod_user(userInfo: UserInfo, db: Session):
        return UserAdminCrud.mod_user(userInfo, db)

    @staticmethod
    def query_user_by_userid(user_id: str, db: Session):
        return UserAdminCrud.query_user_by_userid(user_id, db)

    @staticmethod
    def login(user_id: str, password: str, db: Session):
        if len(user_id) == 0 or len(password) == 0:
            return {"code": ErrorCode.USERID_OR_PASSWORD_IS_EMPTY.value, "message": "用户名或密码不能为空"}

        response = UserAdminCrud.query_user_by_userid(user_id, db)
        if response.get('code') == 0:
            user = response.get('data')
            if user is None:
                return {"code": ErrorCode.USERID_NOT_EXISTS.value, "message": "用户名不存在"}
            else:
                if user.status == UserStatus.NORMAL.value:
                    if authenticate_user(password, user.password):
                        access_token_expires = timedelta(minutes=ACCESS_TOKEN_EXPIRE_MINUTES)
                        access_token = create_access_token(
                            data={"sub": user_id}, expires_delta=access_token_expires
                        )
                        return {'code': ErrorCode.SUCCESS.value, 'message': 'success', 'data': access_token}
                    else:
                        return {"code": ErrorCode.USERID_OR_PASSWORD_ERROR.value, "message": "用户名或密码错误"}
                else:
                    return {"code": ErrorCode.USERID_ALREADY_FROZEN.value, "message": "用户已冻结"}
        else:
            return response

    @staticmethod
    def mod_password(userModPwdInfo: UserModPwdInfo, user_id: str, hashed_password: str, db: Session):
        if authenticate_user(userModPwdInfo.orig_password, hashed_password):
            if userModPwdInfo.new_password == userModPwdInfo.repeated_password:
                userModPwdInfo.new_password = get_password_hash(userModPwdInfo.new_password)
                return UserAdminCrud.mod_password(user_id, userModPwdInfo, db)
            else:
                return {'code': ErrorCode.NEW_PWD_AND_REPEAT_PWD_NOT_EQUAL.value, 'message': '新密码与确认密码不一致'}
        else:
            return {'code': ErrorCode.ORIG_PASSWORD_ERROR.value, 'message': '原密码错误'}
